package com.wetao.testkotlin

import java.lang.IndexOutOfBoundsException

data class TestPoint(val x: Int, val y: Int) {
    operator fun plus(other:TestPoint):TestPoint{
        return TestPoint(x + other.x, y + other.y) //返回新集合
    }

}
//常用下面的扩展函数
/*
operator fun TestPoint.plus(other: TestPoint):TestPoint{
    return TestPoint(x + other.x, y + other.y)
}*/

/*
   a * b times
   a / b div
   a % b mod
   a + b plus
   a - b minus

   优先级 * / % 这三个相同且大于 + -


   += 既可以用plus 也可以用plusAssign
 */

//+= 可变集合
operator fun <T> MutableCollection<T>.plusAssign(element:T) {
    this.add(element)
}

//重载一元运算符-(unaryMinus)和+(unaryPlus)
operator fun TestPoint.unaryMinus() : TestPoint{
    return TestPoint(-x, -y)
}

//!a（not） ++a,a++(inc)  --a,a--(dec)
//==或!=都是(equals) a==b => a?.equals(b) ?: (b==null)，不需要标记operator,因为继承Any父类,不能是扩展函数，因为扩展函数优先级低
//===恒等，不能被重载，引用地址是否相等，基本数据类型值是否相等
//>,<,<=,>=(compareTo) a>=b => a.compareTo(b) >= 0
class TestPerson2(val firstName:String, val lastName:String) :Comparable<TestPerson2>{
    override fun compareTo(other: TestPerson2): Int {
        return compareValuesBy(this, other, TestPerson2::lastName, TestPerson2::firstName)
    }

    //结构声明 （x, y) = p
    operator fun component1() = firstName
    operator fun component2() = lastName
}

//[]
operator fun TestPoint.get(index: Int):Int{
    return when(index){
        0 -> x
        1 -> y
        else -> throw IndexOutOfBoundsException("Invalid coordinate $index")
    }
}

data class TestRectangle(val upperLeft: TestPoint, val lowerRigh:TestPoint)

//in
operator fun TestRectangle.contains(p: TestPoint):Boolean {
    return p.x in upperLeft.x until lowerRigh.x &&
            p.y in upperLeft.y until lowerRigh.y

    //until 是左闭右开区间
    //.. 是左闭右闭区间
}

//.. 运算符使用 rangeTo 重载